import express from 'express'
import expressWs, { Application } from 'express-ws'
import WebSocket from 'ws'

import { Message } from './types'
import { port, ws_path } from './config'

const { app }: { app: Application } = expressWs(express())

const clients: Map<string, WebSocket> = new Map()


app.ws(ws_path, (ws, req) => {
  const id: string = req.query.id as string
  clients.set(id, ws)

  console.log(`${id} - 加入`)

  ws.on('message', (msg: string) => {
    const message: Message = JSON.parse(msg)
    const _ws: WebSocket | undefined = clients.get(message.target)
    if (_ws) {
      _ws.send(msg)
    }
  })

  ws.on('close', () => {
    console.log(`${id} - 离开`)
    clients.delete(id)
  })
})

app.listen(port, () => {
  console.log(`Server on ${port}`)
})
